/*
 * Inspiration for this class:
 *  - http://www.higherpass.com/Android/Tutorials/Working-With-Android-Contacts/
 */

package emt.friendtracking.contact;

import java.text.SimpleDateFormat;
import java.util.Date;

import emt.friendtracking.BaseActivity;
import emt.friendtracking.Data;
import emt.friendtracking.MyApplication;
import emt.friendtracking.R;
import emt.friendtracking.locationmodule.Coordinates;
import emt.friendtracking.locationmodule.CoordinatesHandler;
import emt.friendtracking.locationmodule.CoordinatesUpdateListener;
import emt.friendtracking.locationmodule.LocationIdentifier;
import emt.friendtracking.smsmodule.Message;
import android.content.ContentValues;
import android.database.Cursor;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class EmtContactsActivity extends BaseActivity implements CoordinatesUpdateListener
{
	private static final String TAG = EmtContactsActivity.class.getSimpleName();
	
	private ListView contactsList;
	private LocationIdentifier identifier;
	
//	private BroadcastReceiver sent, delivered;
//	boolean sentRegistered = false, deliveredRegistered =  false;
		
	private String phoneNo, name;
		
    /** Called when the activity is first created. */
    @SuppressWarnings("static-access")
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
    	Log.d(TAG, "onCreated."); //TODO "onCreated."
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts_list_overview);

        //Location stuff
        identifier = LocationIdentifier.getInstance((LocationManager) MyApplication.getAppContext().getSystemService(MyApplication.getAppContext().LOCATION_SERVICE));// new LocationIdentifier((LocationManager) MyApplication.getAppContext().getSystemService(MyApplication.getAppContext().LOCATION_SERVICE));
        Log.d(TAG, "LocationIdentifier is started."); //TODO "LocationIdentifier is started."
		
        contactsList = (ListView) findViewById(R.id.listViewContacts);
        contactsList.setAdapter(fetchContacts());
        
//        sent = new BroadcastSent();
//        delivered = new BroadcastDelivered();
        
        final CoordinatesUpdateListener coordinatesListener = this;
        
        contactsList.setOnItemClickListener(new OnItemClickListener()
        {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				phoneNo = ((TextView) arg1.findViewById(R.id.contact_number_entry)).getText().toString();
				name = ((TextView) arg1.findViewById(R.id.contact_name_entry)).getText().toString();
				identifier.startLocationSearching();
		        CoordinatesHandler.getCoordinatesHandler().addCoordinatesListener(coordinatesListener);
			}        	
		});
    }
    
    public void onDestroy()
    {
    	Log.d(TAG, "onDestroyed."); //TODO "onDestroyed."
    	super.onDestroy();
//    	if (sentRegistered)
//    		unregisterReceiver(sent);
//   		if (deliveredRegistered)
//   			unregisterReceiver(delivered);
    	sms.onDestroy();
    	CoordinatesHandler.getCoordinatesHandler().removeCoordinatesListener(this);
    }
    

	public void onNewCoordinates(Coordinates coordinates)
	{
		Log.i(TAG, "onNewCoordinates (" + coordinates.getAccuracyString() +")"); //TODO "onNewCoordinates (XXX.X)"
		
		if (coordinates.getAccuracy() < BaseActivity.getAccuracy())
		{	
			Log.d(TAG, "Accuracy reached: " + coordinates.getAccuracyString()); //TODO "Accuracy reached: XXX.X"
			
			//BaseActivity.prefs.getString("username", ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getLine1Number())

    		
			try
			{
				Log.d(TAG, "Encrypting."); //TODO "Encrypting."
				String message = Message.make(getUsername(), coordinates.getLongitude(), coordinates.getLatitude());
//				message = StringCryptor.encrypt(new String(BaseActivity.PASSWORD), message);
				Log.d(TAG, "Encrypted."); //TODO "Encrypted."
				
//				Toast.makeText(getBaseContext(), 
//	    				"Message has been encrypted", 
//	    				Toast.LENGTH_SHORT).show();
	    		
				if (phoneNo.length()>0 && message.length()>0) 
	    		{
    				ContentValues values = new ContentValues();
	    			sms.sendASMS(phoneNo, message); //TODO sms.sendASMS
	    			values.put(Data.C_DATE, new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString());
    				values.put(Data.C_SOURCE, phoneNo);
    				values.put(Data.C_SOURCE_NAME, name); //TODO NEED SOMETHING OTHER HERE
    				values.put(Data.C_DIRECTION, Data.DIRECTION.OUTGOING.name());
    				values.put(Data.C_LONGITUDE_ME, coordinates.getLongitude());
    				values.put(Data.C_LATITUDE_ME, coordinates.getLatitude());
    				
    				Data data = new Data();
    				data.insertOrIgnore(values);
    				data.close();
	    		}                
	    		else
	    			Toast.makeText(getBaseContext(), 
	    				"Please contact the developer for this problem.", 
	    				Toast.LENGTH_SHORT).show();
			}
			catch (Exception e)
			{
				e.printStackTrace();
				Toast.makeText(getBaseContext(), 
	    				"Message has been errored", 
	    				Toast.LENGTH_SHORT).show();
			}
	    	CoordinatesHandler.getCoordinatesHandler().removeCoordinatesListener(this);
		}
	}

	private SimpleCursorAdapter fetchContacts()
	{		
		Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] columns = null;
        String where = ContactsContract.RawContacts.ACCOUNT_TYPE + " NOT LIKE ? AND " + ContactsContract.CommonDataKinds.Phone.TYPE + " = ? "; 
        String[] selectionArgs = new String[] { "%facebook", Integer.toString(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) };
        String sortOrder = Contacts.DISPLAY_NAME;
        
        Cursor contacts = managedQuery(uri, columns, where, selectionArgs, sortOrder);

    	String[] FROM = new String[] {ContactsContract.Data.DISPLAY_NAME, Phone.NUMBER };
    	int[] TO = new int[] { R.id.contact_name_entry, R.id.contact_number_entry };
    	
        return new SimpleCursorAdapter(this, R.layout.contact_row, contacts, FROM, TO);
	}

	@Override
	protected boolean isRouteDisplayed()
	{
		return false;
	}
}